package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 计算dateList
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);// 加一天
            timeList.add(begin);
        }
        String timeString = StringUtils.join(timeList, ",");

        // 获取turnoverList
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : timeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);// 00:00
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);// 23:59
            // 构造查询参数
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("begin", beginTime);
            paramMap.put("end", endTime);
            paramMap.put("status", Orders.COMPLETED);
            Double turnover = ordersMapper.getTurnoverByTime(paramMap);
            // 若为null,改变赋值为0,防止换为String后为""
            if (turnover == null) {
                turnover = 0.0;
            }
            // 添加到list中
            turnoverList.add(turnover);
        }
        String turnoverString = StringUtils.join(turnoverList, ",");

        // 构造参数
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(timeString)
                .turnoverList(turnoverString)
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 计算dateList
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);// 加一天
            timeList.add(begin);
        }
        String timeString = StringUtils.join(timeList, ",");

        // 获取newUserList
        ArrayList<Integer> newUserList = new ArrayList<>();
        for (LocalDate localDate : timeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);// 00:00
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);// 23:59
            // 构造查询参数
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("begin", beginTime);
            paramMap.put("end", endTime);
            Integer newUser = userMapper.getNewUserByTime(paramMap);
            // 若为null,改变赋值为0,防止换为String后为""
            if (newUser == null) {
                newUser = 0;
            }
            // 添加到list中
            newUserList.add(newUser);
        }
        String newUserString = StringUtils.join(newUserList, ",");


        // 获取totalUserList
        ArrayList<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : timeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);// 00:00
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);// 23:59
            // 构造查询参数
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("end", endTime);
            Integer totalUser = userMapper.getTotalUserByTime(paramMap);
            // 若为null,改变赋值为0,防止换为String后为""
            if (totalUser == null) {
                totalUser = 0;
            }
            // 添加到list中
            totalUserList.add(totalUser);
        }
        String totalUserString = StringUtils.join(totalUserList, ",");

        // 构造参数
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(timeString)
                .newUserList(newUserString)
                .totalUserList(totalUserString)
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // 计算dateList
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);// 加一天
            timeList.add(begin);
        }
        String timeString = StringUtils.join(timeList, ",");

        // 获取orderCountList
        ArrayList<Integer> orderCountList = new ArrayList<>();
        for (LocalDate localDate : timeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);// 00:00
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);// 23:59
            // 查询抽取方法
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            // 若为null,改变赋值为0,防止换为String后为""
            if (orderCount == null) {
                orderCount = 0;
            }
            // 添加到list中
            orderCountList.add(orderCount);
        }
        // 计算totalOrderCount(每一天的所有订单数求和)
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        // list转string
        String orderCountString = StringUtils.join(orderCountList, ",");

        // 获取validOrderCountList
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : timeList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);// 00:00
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);// 23:59
            // 查询抽取方法
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            // 若为null,改变赋值为0,防止换为String后为""
            if (validOrderCount == null) {
                validOrderCount = 0;
            }
            // 添加到list中
            validOrderCountList.add(validOrderCount);
        }
        // 计算validOrderCount(每一天的有效订单数求和)
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        // list转string
        String validOrderCountString = StringUtils.join(validOrderCountList, ",");

        // 计算orderCompletionRate
        Double orderCompletionRate = 0.0;// 初始值
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        // 构造参数
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(timeString)
                .orderCountList(orderCountString)
                .validOrderCountList(validOrderCountString)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Object status) {
        // 构造查询参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("begin", beginTime);
        paramMap.put("end", endTime);
        paramMap.put("status", status);
        return ordersMapper.getOrderCountByTime(paramMap);
    }

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);// 00:00
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);// 23:59

        // 构造查询参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("begin", beginTime);
        paramMap.put("end", endTime);
        paramMap.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> goodsSalesDTOList = ordersMapper.getSalesTop10(paramMap);
        // 获取nameList
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameString = StringUtils.join(nameList, ",");
        // 获取numberList
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberString = StringUtils.join(numberList, ",");

        // 构造参数
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameString)
                .numberList(numberString)
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 导出近30天Excel报表
     *
     * @param response
     */
    public void export(HttpServletResponse response) {
        // 获取时间参数
        LocalDate begin = LocalDate.now().minusDays(30);// 往前30天
        LocalDate end = LocalDate.now().minusDays(1);// 昨天
        // 获取近30日的数据
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        // 获取文件对象、表单窗口
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(input);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 运营数据报表下的时间
            XSSFRow row1 = sheet1.getRow(1);
            row1.getCell(1).setCellValue("时间：" + begin + "至" + end);
            // 概览数据赋值
            XSSFRow row3 = sheet1.getRow(3);
            // 营业额
            row3.getCell(2).setCellValue(businessData.getTurnover());
            // 订单完成率
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            // 新增用户数
            row3.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row4 = sheet1.getRow(4);
            // 有效订单
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());
            // 平均客单价
            row4.getCell(4).setCellValue(businessData.getUnitPrice());

            // 明细数据赋值
            LocalDate time = begin;
            for (int i = 0; i < 30; i++) {
                // 获取时间段
                LocalDateTime beginDate = LocalDateTime.of(time, LocalTime.MIN);
                LocalDateTime endDate = LocalDateTime.of(time, LocalTime.MAX);
                BusinessDataVO businessDataOne = workspaceService.getBusinessData(beginDate, endDate);
                XSSFRow row = sheet1.getRow(i+7);
                row.getCell(1).setCellValue(time.toString());
                row.getCell(2).setCellValue(businessDataOne.getTurnover());
                row.getCell(3).setCellValue(businessDataOne.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataOne.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataOne.getUnitPrice());
                row.getCell(6).setCellValue(businessDataOne.getNewUsers());
                // 时间每次循环往后加一天
                time = time.plusDays(1);
            }
            // 输出
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            // 关闭资源
            out.close();
            input.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
